package com.dotflat.physicalevaluate.controller;


import com.dotflat.physicalevaluate.domain.importexport.PhysicEvaluateImportRecord;
import com.dotflat.physicalevaluate.domain.pe.PERecord;
import com.dotflat.physicalevaluate.repository.RecordRepository;
import com.dotflat.physicalevaluate.service.EvaluateConclusionService;
import com.dotflat.physicalevaluate.service.PhysicEvaluateExportService;
import com.dotflat.physicalevaluate.service.PhysicEvaluateService;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.page.PagerQuery;
import com.matt.domain.Children;
import com.matt.domain.Classes;
import com.matt.foundation.dto.AreaDetailDTO;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.repository.ChildrenRepository;
import com.matt.service.ChildrenService;
import com.matt.service.ClassesService;
import com.matt.service.remoteCall.SsoCallService;
import com.tuo51.foudation.model.StatusResponse;
import com.tuo51.foudation.utils.CopyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static com.matt.foundation.constant.RequestConstant.TICKET;
import static com.tuo51.evaluate.service.EvaluateV2ExportService.ExportType.WORD;
import static org.springframework.web.bind.annotation.RequestMethod.*;

/**
 * 测评小程序使用的接口
 */

@RestController
@RequestMapping("/peapi/evaluate")
@Api(value = "/peapi/evaluate", tags = "PE - 体质评测")
public class PhysicalEvaluateController {

    @Autowired
    private MemVerificationCache cache;

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private ClassesService classesService;

    @Autowired
    private PhysicEvaluateService physicEvaluateService;

    @Autowired
    private RecordRepository recordRepository;

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    private ChildrenRepository childrenRepository;

    @Autowired
    private PhysicEvaluateExportService exportService;

    @Autowired
    private EvaluateConclusionService conclusionService;

    @ApiOperation(value = "标记单个宝贝单项测评结果，并响应下一个测评的宝宝信息")
    @RequestMapping(value = "/add_record_value", method = RequestMethod.POST)
    public StatusResponse addRecordValue(@RequestHeader(TICKET) String ticket,
                                         String recordId , String childrenId, Integer type, String value) {
        StaffDTO staff = cache.getStaff(ticket);

        Map result = physicEvaluateService.addRecordValue(staff, recordId, childrenId, type, value);

        return StatusResponse.success(result);
    }

    @ApiOperation(value = "批量标记宝贝单项测评结果，values是以childrenId为key，测量值为value的JSON字符串map")
    @RequestMapping(value = "/add_record_values", method = RequestMethod.POST)
    public StatusResponse addRecordValue(@RequestHeader(TICKET) String ticket,
                                         String recordId , Integer type, String values) {
        StaffDTO staff = cache.getStaff(ticket);

        Integer result = physicEvaluateService.addRecordValues(staff, recordId, type, values);

        return StatusResponse.success(result);
    }

    @ApiOperation(value = "增加一个报告, values是按照导入模板体重开始的顺序的数组，JSON字符串")
    @RequestMapping(value = "/add_report", method = RequestMethod.POST)
    public StatusResponse addRecord(@RequestHeader(TICKET) String ticket,
                                    String values ,
                                    String childrenId) {

        StaffDTO staff = cache.getStaff(ticket);


        if (StringUtils.isEmpty(childrenId)){
            throw new BusinessException(ErrorCode.PARAM_CAN_NOT_BLANK, "需要宝宝信息");
        }

        Children children = childrenRepository.findFirstByIdAndAreaId(childrenId, staff.getAreaId());
        if (children == null){
            throw  new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "宝宝不存在");
        }

        PERecord result = physicEvaluateService.addReport(staff, children, values);

        return StatusResponse.success(result);
    }

    @ApiOperation(value = "导入测试结果")
    @RequestMapping(value = "/import_result_raw", method = RequestMethod.POST, headers="content-type=multipart/form-data")
    public StatusResponse importQuestion(@RequestHeader(TICKET) String ticket,
                                         @RequestParam(value = "file", required = false) MultipartFile file,
                                         String classId) {

        StaffDTO staff = cache.getStaff(ticket);

        Classes clazz = classesService.getClassesById(staff.getAreaId(), classId);
        if (clazz == null){
            throw new BusinessException(ErrorCode.CLASSES_NOT_EXIST, "班级不存在");
        }

        PhysicEvaluateImportRecord record = physicEvaluateService.importEvaluateRAW(staff.getAreaId(), staff, clazz, file);

        return StatusResponse.success(record);
    }

    @ApiOperation(value = "下载导入模板")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "classId", value = "是否下载带有小朋友信息的模板", required = false),
            @ApiImplicitParam(name = "ticket", value = "票据", paramType = "header", required = false)

    })
    @RequestMapping(value = "/import_template",  method = GET)
    public StatusResponse getImportTemplate(@RequestHeader(TICKET) String ticket,
                                            String classId ) {

        String url = "https://pe.res.dotflat.cn/template/template_v1.xlsx";
        return StatusResponse.success(url);
    }

    @ApiOperation(value = "导出word报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "recordId", value = "导入记录id，用以集合下载zip包", required = false),
            @ApiImplicitParam(name = "reportId", value = "单个下载某个报告"),
            @ApiImplicitParam(name = "ticket", value = "票据", paramType = "header", required = false)

    })
    @RequestMapping(value = "/export",  method = GET)
    public StatusResponse exportReport(HttpServletRequest req,
                                       @RequestHeader(TICKET) String ticket,
                                       String recordId, String reportId) {

        //导出
        StaffDTO staff = cache.getStaff(ticket);

        //
        AreaDetailDTO area = ssoCallService.getAreaDetailDTO(ticket);

        //exportEvaluateReportToOSS(channel, evaluateRecordId, staff, ExportType.WORD, force);
        String exported_file = exportService.exportEvaluateReportToOSS(null, reportId, staff, area, WORD, true);

        return StatusResponse.success(exported_file);
    }


    @ApiOperation(value = "报告对象")
    @RequestMapping(value = "/report", method = GET)
    public StatusResponse reportDetail(@RequestHeader(TICKET) String ticket,
                                       String reportId) {
        String areaId = cache.getAreaId(ticket);

        PERecord record = recordRepository.findFirstByAreaIdAndIdAndDeletedIsFalse(areaId, reportId);

        return StatusResponse.success(record);
    }


    @ApiOperation(value = "报告结论")
    @RequestMapping(value = "/detail", method = POST)
    public StatusResponse evaluateDetail(HttpServletRequest req,
                                         @RequestHeader(value = TICKET, required = false) String ticket,
                                         String reportId) {


        String areaId = cache.getAreaId(ticket);

        PERecord object = physicEvaluateService.getEvaluateDetail(areaId, reportId);

        Map result = conclusionService.generateReportExtInfo(object);

        result.putAll(CopyUtils.transBean2Map(object));

        return StatusResponse.success(result);
    }

    @ApiOperation(value = "宝宝测评列表",httpMethod = "GET")
    @RequestMapping("/children_reports")
    public StatusResponse childrenEvaluatePage(HttpServletRequest req,
                                               @RequestHeader(value = TICKET, required = false)  String ticket,
                                               String childName,
                                               String classesId,
                                               PagerQuery query) {

        StaffDTO staff = cache.getStaff(ticket);

        //导出

        Page<PERecord> recordPage = physicEvaluateService.getEvaluatePage(staff, classesId, childName, query);

        return StatusResponse.success(recordPage);
    }

    @ApiOperation(value = "删除报告")
    @RequestMapping(value = "/report", method = DELETE)
    public StatusResponse deleteReport(@RequestHeader(TICKET) String ticket,
                                         String reportId) {
        String areaId = cache.getAreaId(ticket);

        PERecord record = recordRepository.findFirstByAreaIdAndIdAndDeletedIsFalse(areaId, reportId);

        if (record == null){
            throw new BusinessException(ErrorCode.EVALUATE_RECORD_NOT_EXIST, "测评报告不存在");
        }

        record.setDeleted(true);
        recordRepository.save(record);

        return StatusResponse.success(record);
    }

}
